import { ElMessage } from 'element-plus'

interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  body?: any;
  headers?: Record<string, string>;
  timeout?: number;
}

// 错误处理类
export class RequestError extends Error {
  constructor(
    public status: number,
    public details: any
  ) {
    super(`请求失败 (状态码: ${status})`);
    this.name = 'RequestError';
  }
}

export async function request<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
  const controller = new AbortController();
  const timeout = options.timeout || 30000;
  const timeoutId = setTimeout(() => controller.abort(), timeout);

  try {
    const startTime = Date.now();
    const apiUrl = url.startsWith('/') ? url : `/${url}`;

    // 添加调试日志
    console.log('发送请求:', {
      url: apiUrl,
      method: options.method,
      headers: options.headers,
      bodyType: options.body ? typeof options.body : 'undefined'
    });

    // 获取认证token
    const token = localStorage.getItem('token');
    const authHeaders = token ? { 'Authorization': `Bearer ${token}` } : {};

    // 发送请求
    const response = await fetch(apiUrl, {
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ...authHeaders,
        ...options.headers
      },
      credentials: 'include',
      signal: controller.signal,
      body: typeof options.body === 'string' ? options.body :
        options.body ? JSON.stringify(options.body) : undefined
    });

    // 记录请求指标
    const duration = Date.now() - startTime;
    logRequestMetrics(response, duration);

    // 获取响应文本并记录
    const responseText = await response.text();
    console.log('请求体:', options.body);
    console.log('收到响应:', {
      status: response.status,
      contentType: response.headers.get('content-type'),
      responseText: responseText.slice(0, 200) // 只记录前200个字符
    });

    // 根据响应头Content-Type解析响应
    let responseData: any;
    const contentType = response.headers.get('content-type') || '';
    if (contentType.includes('application/json') ||
      (responseText.trim().startsWith('{') || responseText.trim().startsWith('['))) {
      const trimmedText = responseText.trim();
      try {
        responseData = trimmedText ? JSON.parse(trimmedText) : null;
      } catch (parseError) {
        console.error('响应JSON解析失败，将原始响应作为错误消息:', {
          status: response.status,
          text: responseText,
          error: parseError instanceof Error ? parseError.message : String(parseError)
        });
        // 如果解析失败，不抛出异常，而是直接使用原始响应文本
        responseData = { message: responseText };
      }
    } else {
      responseData = responseText;
    }

    // 处理错误状态码
    if (!response.ok) {
      // 如果响应数据是对象且包含错误信息，则使用该信息
      const errorMessage = typeof responseData === 'object' && responseData !== null
        ? responseData.message || JSON.stringify(responseData)
        : responseData || response.statusText;
      throw new RequestError(response.status, errorMessage);
    }

    // 处理成功响应
    if (responseData?.success === false) {
      throw new RequestError(response.status, responseData.message || '请求失败');
    }

    return responseData?.data ?? responseData;
  } catch (error) {
    handleRequestError(error, url, options.method);
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}

// 请求指标记录
function logRequestMetrics(response: Response, duration: number): void {
  console.debug('[Request Metrics]', {
    url: response.url,
    status: response.status,
    duration: `${duration}ms`,
    time: new Date().toISOString()
  });
}

// 统一错误处理
function handleRequestError(error: unknown, url: string, method?: string): void {
  if (error instanceof RequestError) {
    console.error('API请求错误:', {
      url,
      method,
      status: error.status,
      details: error.details
    });
  } else if (error instanceof Error) {
    console.error('网络请求错误:', {
      url,
      method,
      message: error.message,
      stack: error.stack
    });
  } else {
    console.error('未知请求错误:', {
      url,
      method,
      error: String(error)
    });
  }
}

export type { RequestOptions };

// 只使用默认导出，移除重复的命名导出
export default { request, RequestError };